﻿using System;
using System.Data;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using Utils;
namespace UI.ModAccount
{
    public partial class AccountMenuMgr : System.Web.UI.Page
    {

        MenuBiz menuBiz = new MenuBiz();
        RoleBiz roleBiz = new RoleBiz();
       // DefDicBiz defineDictionary = new DefDicBiz();
        IBizSQL bizSQL = new BizSQL();
        string strAimTable = "Sys_AccountMenu";

        string account = string.Empty;//定义传过来的帐号ID
        string sessionAccount = string.Empty;
        //存储该帐号菜单的所有ID,在生成菜单树的时候，让已经具有的显示选中状态
        private ArrayList alAccountID = new ArrayList();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["user"] != null)
            {
                User user = Session["user"] as User;
                sessionAccount = user.Account;
            }
            else
            {
                JSUtility.Alert(this, "您没有登录!请先登录。");
                return;
            }
            if (Request.QueryString["Account"] == null)
            {  //弹出提示窗口
                Response.Write("<script>window.alert('只有选择了帐号才能到该页面操作！')</script>");
                return;
            }
            account = Request.QueryString["Account"].ToString().Trim();
            if ((account == "0") || (string.IsNullOrWhiteSpace(account)))
            {
                //弹出提示窗口
                Response.Write("<script>window.alert('只有选择了帐号才能到该页面操作！')</script>");
                return;
            }

            //获取已经有的角色

            DataTable dt = roleBiz.GetUserRole(account); //SysRoleID
            //绑定所有 角色
            DataSet ds = bizSQL.ExecSQL2("SELECT [SysRoleID] AS ID, [Name] FROM [Sys_SysRole] order by AbsIndex ");
            for (int r = 0; r < ds.Tables[0].Rows.Count; r++)
            {
                CheckBox cb = new CheckBox();

                cb.ID = ds.Tables[0].Rows[r]["ID"].ToString();
                cb.Text = ds.Tables[0].Rows[r]["Name"].ToString();

                for (int n = 0; n < dt.Rows.Count; n++)//默认已有的 勾选上
                {
                    if (ds.Tables[0].Rows[r]["ID"].ToString() == dt.Rows[n]["SysRoleID"].ToString())
                    { cb.Checked = true; }

                }
                ph.Controls.Add(cb);
            }
            //显示菜单列表
            if (!IsPostBack)
            {


                /* defineDictionary.InitDropDownList(ds.Tables[0], ddlRole);
                 //首先确定有没有角色
                string strSQL=" select SysRoleID from Sys_Account  Where Account='" + account+"'";
                DataSet ds2 = menuBiz.ExecSQL2(strSQL);
                string tmpRole = ds2.Tables[0].Rows[0]["SysRoleID"].ToString();
                if (!string.IsNullOrWhiteSpace(tmpRole))
                {
                    ddlRole.SelectedValue = tmpRole;
                }
                 */

                //然后下一步
                lbAccount.Text = account;
                //第一步：删除系统定义已经删除而帐号还具有的菜单
                string strDeleteSQL = "DELETE FROM " + strAimTable;
                strDeleteSQL += " WHERE Account='" + account + "' AND MainMenuID NOT IN (SELECT MainMenuID FROM Sys_MainMenu WHERE State='Y')";
                bizSQL.ExecSQL(strDeleteSQL);
                //取出该帐号定义过的菜单ID（上面把不存在的已经删除）并填充到ArrayList alAccountID
                //alAccountID是用来实现该帐号的菜单在显示的时候选中
                DataTable dtMainMenuID = menuBiz.GetOneInfo(account);

                int count = dtMainMenuID.Rows.Count;
                for (int i = 0; i < count; i++)
                {
                    alAccountID.Add(dtMainMenuID.Rows[i]["MainMenuID"].ToString());
                }
                Create_MainMenu_TreeView();
                this.MainMenuTreeView.Attributes.Add("onclick", "CheckEvent()");
            }

        }

        private void Create_MainMenu_TreeView()
        {
            MainMenuTreeView.Nodes.Clear();
            //取出菜单数据
            string strSQL = "select MainMenuID,ParentID,MenuName from Sys_MainMenu where [State]='Y' order by AbsIndex DESC";
            DataSet ds = bizSQL.ExecSQL2(strSQL);
            if (ds == null)
            {
                return;
            }
            else
            {
                this.ViewState["ds"] = ds;

                //调用递归函数，完成树形结构的生成
                AddTree(0, (TreeNode)null);
            }
        }
        //递归添加树的节点
        private void AddTree(int ParentID, TreeNode pNode)
        {
            DataSet ds = (DataSet)this.ViewState["ds"];
            DataView dvTree = new DataView(ds.Tables[0]);
            //过滤ParentID,得到当前的所有子节点
            dvTree.RowFilter = "[ParentID] = " + ParentID;

            foreach (DataRowView Row in dvTree)
            {
                TreeNode Node = new TreeNode();

                if (pNode == null)
                {    //添加根节点

                    Node.Text = Row["MenuName"].ToString();
                    Node.Value = Row["MainMenuID"].ToString();
                    MainMenuTreeView.Nodes.Add(Node);
                    //if (alAccountID.Contains(Row["MainMenuID"].ToString()))
                    if (alAccountID.IndexOf(Row["MainMenuID"].ToString()) != -1)
                    {
                        Node.Checked = true;
                    }
                    //Node.Expanded = true;
                    AddTree(Int32.Parse(Row["MainMenuID"].ToString()), Node);    //再次递归
                }
                else
                {   //̀添加当前节点的子节点
                    Node.Text = Row["MenuName"].ToString();
                    Node.Value = Row["MainMenuID"].ToString();
                    pNode.ChildNodes.Add(Node);
                    //if (alAccountID.Contains(Row["MainMenuID"].ToString()))
                    if (alAccountID.IndexOf(Row["MainMenuID"].ToString()) != -1)
                    {
                        Node.Checked = true;
                    }
                    //Node.Expanded = true;
                    AddTree(Int32.Parse(Row["MainMenuID"].ToString()), Node);     //再次递归
                }
            }
        }

        //点击按纽事件,把管理员为此帐号选择的菜单存到数据库Sys_AccountMenu表里面
        protected void btnConfigMenu_Click(object sender, EventArgs e)
        {


            try
            {
                //不清空角色  两种设置同时作用
               // string sql = "delete from Sys_Account_Role  Where Account='" + account + "'";
               // new AccountBiz().ExecSQL(sql);
                //插入选定的菜单
                InsertAllSelectNodeID(MainMenuTreeView.Nodes);
                Response.Redirect("~/ModAccount/AccountMenuMgr.aspx?Account=" + account);
            }
            catch (Exception ex)
            {
                Response.Write("错误，错误原因：" + ex.Message);
                Response.End();
            }
        }
        void InsertAllSelectNodeID(TreeNodeCollection tnc)
        {
            foreach (TreeNode node in tnc)
            {
                //string strInsertSQL = "INSERT INTO Sys_AccountMenu (AccountID,MainMenuID) VALUES (" + iAccountID + "," + Int32.Parse(node.Value.ToString()) + ")";
                //插入数据
                if (node.Checked)//如果选中了此菜单
                {
                    string strSQL = "SELECT * FROM Sys_AccountMenu WHERE Account='" + account + "' AND MainMenuID = " + Int32.Parse(node.Value.ToString());
                    if (bizSQL.ExecSQL2(strSQL).Tables[0].Rows.Count <= 0)//该条记录不存在
                        bizSQL.ExecSQL("INSERT INTO Sys_AccountMenu (Account,MainMenuID) VALUES ('" + account + "'," + Int32.Parse(node.Value.ToString()) + ")");
                }
                else ////如果没有选中此菜单
                {
                    bizSQL.ExecSQL("DELETE FROM Sys_AccountMenu WHERE Account='" + account + "' AND MainMenuID = " + Int32.Parse(node.Value.ToString()));
                }
                if (node.ChildNodes.Count != 0)
                    InsertAllSelectNodeID(node.ChildNodes);
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/ModAccount/AccountList.aspx", false);
        }

        protected void btnSetRole_Click(object sender, EventArgs e)
        {
            try
            {
                int n = 0;

                foreach (Control c in ph.Controls)
                {
                    if (c is CheckBox)
                    {
                        CheckBox cb = (CheckBox)c;
                        string sysRoleID = cb.ID;
                        if (cb.Checked)
                        {
                            n++;
                            //写入数据库
                            bizSQL.ExecSQL(" if not exists (select * from Sys_Account_Role  where  Account= '" + account + "' and SysRoleID = '" + sysRoleID + "') begin "
                                            + " INSERT INTO Sys_Account_Role (Account, SysRoleID, AbsIndex)values( '" + account + "', '" + sysRoleID + "'," + n + ") end ");
                        }
                        else
                        {
                            bizSQL.ExecSQL("DELETE FROM Sys_Account_Role  WHERE Account='" + account + "'  and SysRoleID ='" + sysRoleID + "'");
                        }
                    }
                }
                if (n > 0)
                {
                    //通过角色设置了，还需要删除通过单个菜单设置（第二种设置方式）的内容
                    bizSQL.ExecSQL("DELETE FROM Sys_AccountMenu WHERE Account='" + account + "'");
                    JSUtility.Alert(this, "成功设置角色" + n + "个");
                }

            }
            catch (Exception ee)
            { JSUtility.Alert(this, "设置角色失败" + ee.Message); }
            /* string role = ddlRole.SelectedValue;
             if (role == "0")
             {
                 JSUtility.Alert(this, "请选择角色");
                 return;
             }
             try
             {
                 string sql = "DELETE FROM Sys_AccountMenu  WHERE Account='" + account + "'; Update Sys_Account Set SysRoleID='" + role + "' Where Account='" + account + "'";
                 bizSQL.ExecSQL(sql);
                 JSUtility.Alert(this, "设置角色成功");
             }
             catch(Exception ee)
             { JSUtility.Alert(this, "设置角色失败"+ee.Message); }
             */
        }




        //class
    }
}
